package com.example.controller;

import com.example.pojo.Result;
import com.example.utils.GdalUtil;
import com.example.utils.readGDB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLDecoder;
import java.util.Objects;

import static com.example.utils.DealZipUtil.dealZip;


@Slf4j
@RestController
public class uploadController {

    @PostMapping("/upload")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("文件为空，请重新上传");
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            //获取当前项目的classes绝对路径
            String classespath = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath();
            //解决文件路径中的空格问题
            String decodeClassespath = URLDecoder.decode(classespath,"utf-8");
            // 上传文件路径
            File dest = new File( new File(decodeClassespath).getAbsolutePath() + "/upload/" + fileName);
            // 执行上传
            file.transferTo(dest);
            // 设置解压压缩包的文件夹
            File unzip = new File( decodeClassespath + "/unzip/");
            // 执行解压，返回解压后的文件名
            String s1 = dealZip(dest, unzip);
            // 使用gdal解析gdb文件信息
            readGDB readGDB = new readGDB();
            readGDB.GdbSource(unzip.toString() +"/" + s1);
            GdalUtil.importGdbToDatabase(unzip.toString() +"/" + s1);
            return Result.success("文件上传成功: " + fileName);
        } catch (Exception e) {
            log.info("上传失败",e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
}
